// 简单的 ArrayList 实现 - 使用 cz_std
const std = @import("std");
const cz_std = @import("cz_std.zig");
const Allocator = cz_std.Allocator;

pub fn ArrayList(comptime T: type) type {
    return struct {
        const Self = @This();
        
        items: []T,
        capacity: usize,
        allocator: Allocator,
        
        pub fn init(allocator: Allocator) Self {
            return Self{
                .items = &[_]T{},
                .capacity = 0,
                .allocator = allocator,
            };
        }
        
        pub fn deinit(self: *Self) void {
            if (self.capacity > 0) {
                self.allocator.free(self.items.ptr[0..self.capacity]);
            }
        }
        
        pub fn append(self: *Self, item: T) !void {
            if (self.items.len >= self.capacity) {
                try self.ensureCapacity(self.capacity + 1);
            }
            
            // 扩展 items 切片
            self.items.ptr[self.items.len] = item;
            self.items.len += 1;
        }
        
        pub fn toOwnedSlice(self: *Self) ![]T {
            const result = try self.allocator.alloc(T, self.items.len);
            @memcpy(result, self.items);
            self.deinit();
            self.* = Self.init(self.allocator);
            return result;
        }
        
        fn ensureCapacity(self: *Self, new_capacity: usize) !void {
            if (new_capacity <= self.capacity) return;
            
            const better_capacity = @max(new_capacity, self.capacity * 2);
            const new_memory = try self.allocator.alloc(T, better_capacity);
            
            if (self.items.len > 0) {
                @memcpy(new_memory[0..self.items.len], self.items);
            }
            
            if (self.capacity > 0) {
                self.allocator.free(self.items.ptr[0..self.capacity]);
            }
            
            self.items = new_memory[0..self.items.len];
            self.capacity = better_capacity;
        }
    };
}

// 简单的 Writer 实现用于 ArrayList(u8)
pub const ArrayListWriter = struct {
    list: *ArrayList(u8),
    
    pub fn print(self: *ArrayListWriter, comptime fmt: []const u8, args: anytype) !void {
        // 使用 std.fmt.bufPrint 进行格式化
        var buf: [4096]u8 = undefined;
        const result = try std.fmt.bufPrint(&buf, fmt, args);
        for (result) |byte| {
            try self.list.append(byte);
        }
    }
};

pub fn arrayListWriter(list: *ArrayList(u8)) ArrayListWriter {
    return ArrayListWriter{ .list = list };
}
